package multiThreaded;

import java.net.MalformedURLException;

import singleThreaded.PageRetriever;

/**
 * A page retriever thread.
 * @author DoubleS
 * @version 1.0
 */
public class PageRetrieverThread implements Runnable
{
  /**
   * The url buffer.
   */
  private UrlBuffer my_url_buffer;
  
  /**
   * The web page buffer.
   */
  private PageBuffer my_page_buffer;
  
  /**
   * The max number of links need to visit.
   */
  private final int my_limit;
  /**
   * Construct a PageRetrieverThread.
   * @param the_url_buffer The url buffer.
   * @param the_page_buffer The page buffer.
   * @param the_max_count The max number of links need to visit.
   */
  private boolean is_block = false;
  public PageRetrieverThread(final UrlBuffer the_url_buffer, final PageBuffer the_page_buffer, 
                          final int the_max_count)
  {
    my_url_buffer = the_url_buffer;
    my_page_buffer = the_page_buffer;
    my_limit = the_max_count;

  }
  /**
   * {@inheritDoc}
   */
  public void run()
  {
    is_block = false;
    //System.out.println("I'm in the Page Retriever Thread");
    WebPage the_page;
    PageRetriever the_retriever;
    
    // Retrieve the web page as long as the total links doesn't exceed my_max_count
    // and the 2 buffers are not empty.
    //while (my_url_buffer.getTotalLinks() <= my_limit && 
    //      !(my_page_buffer.isEmtpy() || my_url_buffer.isEmpty()))
    
    while (my_url_buffer.getNumVisitedPages() <= my_limit)
    {      
      //Get a new unvisited link from the buffer
      is_block = true;
      final String the_link = my_url_buffer.retrieveAnUnvisitedLink();
      is_block = false;
      try
      {
        the_retriever = new PageRetriever(the_link);
        the_page = new WebPage(the_retriever.retrievePageSource(), the_retriever.getUrl());
        my_page_buffer.addToPageBuffer(the_page);
      }
      catch (final MalformedURLException e)
      {
        System.out.println("Error link: " + the_link);
        e.printStackTrace();
      }
    }
  }
}
